<template>
	<div style="font-size: 14px;">
		<div class="gongneng_box">
			<div style="display: flex;align-items: center;">
				<div v-if="!showHeightSearch" style="display: flex;align-items: center;">
					<el-select 
						v-model="formItem.field" 
						placeholder="请选择" 
						@change="fieldChange(formItem)">
						<el-option 
							v-for="item in options" 
							:key="item.field" 
							:label="item.name"
							:value="item.field">
						</el-option>
					</el-select>
					
					<!-- 条件值 -->
					<el-col 
						style="margin-left: 10px;" 
						:span="formItem.form_type === 'datetime' || formItem.form_type === 'date' ? 13 : 8">
						<el-select 
							v-if="formItem.form_type === 'select'" 
							v-model="formItem.value"
							placeholder="请选择筛选条件">
							<el-option 
								v-for="item in formItem.setting" 
								:key="item" 
								:label="item" 
								:value="item" />
						</el-select>
						<div style="width: 470px;" v-else-if="formItem.form_type === 'date' || formItem.form_type === 'datetime'">
							<el-date-picker
								v-model="formItem.value"
								:value-format="formItem.form_type === 'date' ? 'yyyy-MM-dd' : 'yyyy-MM-dd HH:mm:ss'"
								:type="formItem.form_type === 'date' ? 'daterange' : 'datetimerange'"
								style="padding: 0px 10px;" 
								range-separator="-" 
								start-placeholder="开始日期"
								end-placeholder="结束日期" />
						</div>
							<div style="width: 300px;" v-else-if="formItem.form_type === 'user' || formItem.form_type === 'user-multiple'">
								<xh-user-cell
									:item="formItem" 
									@value-change="arrayValueChange" />
							</div>
						<el-input 
							v-else 
							v-model="formItem.value" 
							placeholder="请输入筛选条件" />
					</el-col>	
					<!-- 搜索 -->
					<el-button 
						style="margin-left: 15px; color: #fff; background-color: #b5060d;"
						@click="onSearch()">搜索</el-button>
				</div>
			</div>
			<div style="display: flex;align-items: center;">
				
				<div v-if="crmType == 'lawcase'">
					<el-popover
						placement="left"
						v-model="visible">
						<p style="line-height: 20px;">
							请选择案件类型
						</p>
						<div style="text-align: right;margin-top: 15px;">
							<el-button 
								size="mini" 
								@click="clickBtn('zixun')">非诉咨询</el-button>
							<el-button 
								size="mini" 
								@click="clickBtn('fuwu')">非诉服务</el-button>
							<el-button
								size="mini" 
								@click="clickBtn('susong')">诉讼案件</el-button>
							<el-button
								size="mini" 
								@click="clickBtn('xingshi')">刑事案件</el-button>
						</div>
						<el-button
							type="primary" 
							size="mini"  
							slot="reference"
							icon="el-icon-edit" >{{title}}</el-button>
					</el-popover>
				</div>
				<div v-else-if="crmType == 'customer' || crmType == 'contract'">
					<el-button
						v-if="canSave"
						icon="el-icon-edit" 
						class="buttomc"
						 @click="clickBtn(crmType)">{{title}}</el-button>
				</div>
				
					 
					 
				<el-dropdown
					trigger="click"
					@command="handleTypeDrop">
					<el-button icon="el-icon-arrow-down" class="buttomc">批量操作</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item
							v-for="(item, index) in moreTypes"
							:key="index"
							:command="item.type">{{ item.name }}</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
				<el-button 
					icon="el-icon-search"
					plain 
					style="margin-left: 15px;border: 1px solid #b5060d;color: #b5060d; "
					@click="heightSearch">高级搜索</el-button>
			</div>
		</div>
		<div v-if="showHeightSearch" style="margin-top: 0px;">
			<el-row style="padding:20px">
				<el-col 
					:span="12" 
					v-for="(formItem, index) in form"
					:key="formItem.field" 
					style="margin-top: 15px;">
					<div style="padding-bottom: 15px;">{{formItem.name}}</div>
					<el-select
						v-if="formItem.form_type === 'select'" 
						v-model="formItem.value"
						placeholder="请选择筛选条件"
						class="heightitem">
						<el-option 
							v-for="item in formItem.setting" 
							:key="item" 
							:label="item" 
							:value="item" />
					</el-select>
					<el-date-picker
						v-else-if="formItem.form_type === 'date' || formItem.form_type === 'datetime'"
						v-model="formItem.value"
						:value-format="formItem.form_type === 'date' ? 'yyyy-MM-dd' : 'yyyy-MM-dd HH:mm:ss'"
						:type="formItem.form_type === 'date' ? 'daterange' : 'datetimerange'"
						style="padding: 0px 10px;" 
						range-separator="-" 
						start-placeholder="开始日期"
						end-placeholder="结束日期" 
						class="heightitem"/>
					<xh-user-cell
						v-else-if="formItem.form_type === 'user' || formItem.form_type === 'user-multiple'"
						:item="formItem" 
						@value-change="arrayValueChanges($event,index)" 
						:width="300"/>
					<el-input 
						v-else 
						v-model="formItem.value" 
						placeholder="请输入筛选条件" 
						class="heightitem"/>
				</el-col>
				<el-col
					:span="24" >
					<!-- 搜索 -->
					<el-button 
						style="margin-top: 15px; color: #fff; background-color: #b5060d;"
						@click="onHeightSearch()">搜索</el-button>
					<!-- 重置 -->
					<el-button
						style="margin-top: 15px; color: #b5060d; border:1px solid #b5060d;"
						@click="onHeightSearchReset()">重置</el-button>
				</el-col>
			</el-row>
		</div>
		<!-- 新建 -->
		<c-r-m-create-view
			v-if="isCreate"
			:crm-type="createCRMType"
			:action="createActionInfo"
			:form-data="formData"
			@save-success="createSaveSuccess"
			@hiden-view="hideView"/>
			
		<!-- 导出 -->
		<c-r-m-export
			:show="showCRMExport"
			:crm-type="crmType"
			:search="search"
			:scene_id="scene_id"
			:actiontype="actiontype"
			:filter-arr="filterArr"
			:export-params="exportParams"
			@close="showCRMExport=false"/>

		<!-- 批量导入 -->
		<el-dialog title="批量导入" :visible.sync="showBatchImport" :before-close="handleImportClose">
			<el-form ref="importForm" :model="importForm" :rules="importRules" label-width="80px">
				<el-form-item label="案件类型" prop="type">
					<el-select v-model="importForm.type" filterable>
						<el-option v-for="(item,index) in type" :key="index" :label="item.label" :value="item.value"></el-option>
					</el-select>
					<el-button style="margin-left: 20px" type="primary" @click="handleImportDown">下载模板</el-button>
				</el-form-item>
				<el-form-item label="文件上传" prop="file">
					<el-upload ref="upload" accept=".xlsx" :limit="1" :headers="fileAPI" :action="doUpload" multiple :before-upload="beforeAvatarUpload" :onError="uploadError" :on-remove="uploadRemove" :on-success="uploadSuccess" :file-list="fileList" :auto-upload="false">
                        <el-button type="primary" plain>选择文件</el-button>						
                        <div class="el-upload__tip" style="margin-top: 0;" slot="tip">只能上传xlsx文件，且不超过20Mb</div>
                    </el-upload>
					<el-button type="success" @click="submitUpload">上传到服务器</el-button>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="showBatchImport = false">取 消</el-button>
				<el-button type="primary" :loading="loading" @click="handleBatchImport">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 批量导入 End -->
		
	</div>
</template>

<script>
	import { mapGetters } from 'vuex'
	import CRMCreateView from '../CRMCreateView'
	import CRMExport from '../CRMExport'
	import { filterIndexfields } from '@/api/setting/setting'
	import { XhUserCell } from '@/components/user'
	import { crmLawcaseImport } from '@/api/lawcase/lawcase'
	import {
		formatTimeToTimestamp,
		objDeepCopy
	} from '@/utils'
	
	export default {
		components: {
			CRMCreateView,
			CRMExport,
			XhUserCell
		},
		props: {
			// CRM类型
			crmType: {
			  type: String,
			  default: ''
			},
			searchtype: {
			  type: [String,Number],
			  default: ''
			},
			actiontype: {
			  type: [String,Number],
			  default: ''
			},
			// 表单数据
			formData: {
				type: Object,
				default: () => {
					return {}
				}
			},
			// 搜索条件
			search: {
			  type: String,
			  default: ''
			},
			scene_id: {
			  type: [Number, String],
			  default: ''
			},
			filterArr: {
			  type: Array,
			  default: () => {
			    return []
			  }
			},
		},
		watch: {
			showHeightSearch: {
				handler(val) {
					if (!val) {
						if (this.form.length == 0) {
							this.form = []
						}
					}
				},
				deep: true,
				immediate: true
			}
		},
		
		data() {
			return {
				// 搜索
				form: [],
				formItem:{
					field: '',
					name: '',
					form_type: '',
					value: ''
				},
				options: [],
				value: '',
				showHeightSearch:false,
				
				
				/** 更多操作 */
				moreTypes: [],
				
				/** 创建的相关信息*/
				createActionInfo: { type: 'save' },
				createCRMType: '',
				isCreate: false, 
				visible:false,
				// 导出选中参数
				exportParams: {},
				// 导出
				showCRMExport: false,
				//批量导入
				loading: false,
				fileList: [],
				fileAPI: {
					Authkey: '', 
					Sessionid: '',
				},
				doUpload: window.BASE_URL + 'setting/upload',
				showBatchImport: false,
				type: [
					{value: 'zixun', label: '非诉咨询'},
					{value: 'fuwu', label: '非诉服务'},
					{value: 'susong', label: '诉讼案件'},
					{value: 'xingshi', label: '刑事案件'},
				],
				importForm: {
					type: '',
					file: [],
				},
				importRules: {
					type: [
                        { required: true, message: '请选择案件类型', trigger: 'blur' },
                    ],
					file: [
                        { required: true, message: '请上传文件', trigger: 'blur' },
                    ],
				},
			}
		},
		mounted() {
			// 更多操作
			if (this.allAuth[this.crmType] && this.allAuth[this.crmType].excelexport) {
				this.moreTypes.push({ type: 'out', name: '导出' })
			}

			if (this.allAuth[this.crmType] && this.allAuth[this.crmType].import) {
				this.moreTypes.push({ type: 'import', name: '批量导入' })
			}

			let Authkey = JSON.parse(localStorage.getItem('authKey'));
			let Sessionid = JSON.parse(localStorage.getItem('sessionId'));
			this.fileAPI.Authkey = Authkey.data;
			this.fileAPI.Sessionid = Sessionid.data;
			
			this.getFieldList()
			
		},
		computed: {
			...mapGetters(['allAuth']),
			canSave() {
				if(this.crmType == "customer" || this.crmType == "lawcase" || this.crmType == "contract") {
					return this.allAuth[this.crmType].save
				}else{
					return false
				}
				
			},
			title() {
				if(this.crmType == "customer") {
					return '新建客户'
				}else if(this.crmType == "lawcase"){
					return '新建案件'
				}else if(this.crmType == "contract"){
					return '新建顾问'
				}
			}
		},
		methods: {
			
			// 点击按钮
			clickBtn(type) {
				this.createCRMType = this.crmType
				let actionTypes
				if(type == "customer") actionTypes = 16
				if(type == "zixun") actionTypes = 13
				if(type == "fuwu") actionTypes = 14
				if(type == "susong") actionTypes = 15
				if(type == "xingshi") actionTypes = 16
				if(type == "contract") actionTypes = 10
				
				if(type == "customer"){
					this.createActionInfo = { type: 'save',actiontype:actionTypes}
				}else{
					this.createActionInfo = { type: 'save',actiontype:actionTypes , relevant:type  }
				}
				
				this.isCreate = !this.isCreate
			},
			
			// 更多操作
			handleTypeDrop(command, params = {}) {
				if (command == 'out') {
					// 导出
					let paramsData = {}
					if (params.__export) {
						paramsData = params
						delete paramsData.__export
					} else {
						paramsData = {}
					}
					this.exportParams = paramsData
					this.showCRMExport = true
				} else if (command == 'enter') {
					// 导入
				} else if (command == 'import'){
					this.showBatchImport = true;
				}
			},
			
			
			// 关闭新建弹窗
			hideView() {
				this.isCreate = false
				this.$emit('hide-view')
			},
			
			// 创建数据页面 保存成功
			createSaveSuccess(data) {
				this.$emit('createSaveSuccess',data)
			},
			
			
			
			// 搜索板块
			/**
			 * 用户
			 */
			arrayValueChange(data) {
				if(data.value.length > 0){
					this.formItem["value"]  = data.value
				}else{
					this.formItem["value"]  = ''
				}
				
			},
			
			arrayValueChanges(data,index) {
				if(data.value.length > 0){
					this.form[index]["value"]  = data.value
				}else{
					this.form[index]["value"] = ''
				}
			},
			
			getFieldList()  {
				 console.log(this.crmType)
				filterIndexfields({
						types: 'crm_' + this.crmType,
						actiontype:this.searchtype
					})
					.then(res => {
						if(this.crmType != 'customer'){
							this.formItem = res.data[0]
						}
						this.form = res.data
						this.options = res.data
						
					})
					.catch(() => {})
			},
			fieldChange(formItem) {
				const obj = this.options.find(item => {
					return item.field === formItem.field
				})
				if (obj) {
					formItem.form_type = obj.form_type
					formItem.name = obj.name
					if (formItem.form_type == 'select') {
						formItem.setting = obj.setting || []
						formItem.value = ''
					} else if (
						formItem.form_type === 'date' ||
						formItem.form_type === 'datetime' ||
						formItem.form_type === 'user'||
						formItem.form_type === 'user-multiple'
					) {
						formItem.value = []
					}else{
						formItem.value = ''
					}
				}
				
			},
			
			// 搜索
			onSearch(){
				this.$emit("on-search",this.formItem)
			},
			
			// 高级搜索显示
			heightSearch(){
				this.showHeightSearch = !this.showHeightSearch
			},
			onHeightSearch(){
				this.$emit("on-height-search",this.form)
			},
			onHeightSearchReset(){
				this.form.map((formItem)=>{
					if(formItem.value != undefined){
						if (formItem.form_type == 'select') {
							formItem.value = ''
						} else if (
							formItem.form_type === 'date' ||
							formItem.form_type === 'datetime'
						) {
							formItem.value = []
						}else if (
							formItem.form_type === 'user'||
							formItem.form_type === 'user-multiple'
						) {
							formItem.value = []
							// 补充
							
						}else{
							formItem.value = ''
						}
					}
				})
				this.$emit("on-height-search",this.form)
			},

			//下载模板
			handleImportDown (e) {
				if(!this.importForm.type){
					return this.$message.error('请选择案件类型!');
				}

				if(this.importForm.type == 'zixun'){
					//非诉咨询
					window.open(window.DOWN_URL + '/download/zixun.xlsx')
				}else{
					//其它
					window.open(window.DOWN_URL + '/download/susong.xlsx')
				}
			},

			//提交批量导入
			handleBatchImport(){
				if(this.fileList.length == 0){
					return this.$message.error('请上传文件')
				}
				this.importForm.user_id = JSON.parse(localStorage.getItem('userInfoId')).data;
				this.importForm.file = this.fileList[0].save_name;
				this.$refs.importForm.validate((valid) => {
					if (valid) {
						this.loading = true;
						crmLawcaseImport(this.importForm).then(res => {
							this.showBatchImport = false;
							if(res.data){
								this.loading = false
							}
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},

			//上传到服务器
			submitUpload(){
				this.$refs.upload.submit();
			},

			//上传前的较验
            beforeAvatarUpload(file){
                const extension = file.name.split('.')[1] === 'xlsx'
                const isLt10M = file.size / 1024 / 1024 < 20
                if (!extension) {
                    this.$message.error('上传模板只能是 xlsx 格式');
                }
                if (!isLt10M) {
					this.$message.error('上传模板大小不能超过 20MB!');
                }
                return extension && isLt10M
            },

			//上传失败
			uploadError(){
				this.$message.error('上传失败，请重试!');
			},

			//删除上传
			uploadRemove(file){
				this.$message.success('删除成功!');
				this.fileList = [];
			},

			//上传成功
			uploadSuccess(file,fileList){
				if(file.code != 200){
					this.$message.success('上传失败，请重试!');
				}else{
					this.fileList = file.data;
					this.$message.success('文件上传成功!');
				}
			},

			//关闭批量导入
			handleImportClose(){
				this.showBatchImport = false;
				this.$refs.importForm.resetFields();
			}
			
		},
	}
</script>

<style scoped>
	.buttomc{
		margin-left: 15px; 
		color: #fff; 
		background-color: #b5060d;
	}
	.gongneng_box {
		margin-top: 10px;
		display: flex;
		justify-content: space-between;
		font-size: 14px;
	}
	.heightitem{
		width: 300px;
	}
</style>